<template>
  <view class="publish-container">
    <!-- 图片上传区域 -->
    <view class="image-upload">
      <view class="image-box" :key="index" v-if="img !== ''">
        <image :src="img" class="preview-img" mode="aspectFill" />
      </view>
      <view class="image-box add-box" @tap="chooseImage">
        <text class="plus">+</text>
      </view>
    </view>

    <!-- 标题输入 -->
    <input v-model="title" placeholder="添加标题" class="input-title" />

    <!-- 正文输入 -->
    <textarea v-model="content" placeholder="添加正文" class="input-content" />

    <!-- 拍摄建议 -->
    <textarea v-model="suggestion" placeholder="拍摄建议（选填）" class="input-content" />

    <!-- 拍摄日期选择 -->
    <view class="form-item">
      <text class="label">拍摄时间点：</text>
      <div class="time">
        <picker mode="date" :value="shootDate" @change="onDateChange">
          <view class="picker">{{ shootDate?shootDate +' >': '日期 >' }}</view>
        </picker>
        <picker mode="time" :value="shootTime" @change="onTimeChange">
          <view class="picker">{{ shootTime?shootTime+" >" : '时间 >' }}</view>
        </picker>
      </div>
    </view>

  <!-- 拍摄城市选择（选填） -->
<view class="form-item">
  <text class="label">拍摄城市：</text>
  <picker :range="cities" range-key="name" @change="onCityChange">
    <view class="picker">{{selectedCity ? selectedCity.name +" >": '请选择城市（选填）'}}</view>
  </picker>
</view>

<!-- 拍摄景点选择（选填，仅在选中城市后显示） -->
<view class="form-item" v-if="selectedCity && spots.length">
  <text class="label">拍摄景点：</text>
  <picker :range="spots" range-key="name"   @change="onSpotChange">
    <view class="picker">{{ selectedSpot ? selectedSpot.name+" >" : '请选择景点（选填）' }}</view>
  </picker>
</view>


    <!-- 拍摄详细地点 -->
    <view class="form-item location-picker">
      <text class="label">详细地点：</text>
      <view class="picker" @tap="chooseLocation">
        {{ locationName || '点击搜索位置 >' }}
      </view>
    </view>

    <!-- 发布按钮 -->
    <button class="submit-btn" type="primary" @tap="submit">发布笔记</button>
  </view>
</template>
<script>
import { uploadPostWithFile,getAllCities,getSpotsByCity } from '../../api'

export default {
  data() {
    return {
      img: '',
      title: '',
      content: '',
      suggestion: '',
      shootDate: '',
      shootTime: '',
      // 城市和景点相关字段（新增）
      cities: [], // 示例城市列表，可替换为后端请求
      selectedCity: '',
      spots: [], // 景点列表
      selectedSpot: '', // 景点名称
      selectedSpotId: null, // 景点 ID
      locationName: "", // 选中的地点名
      latitude: null,
      longitude: null,
      address: "",
      token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJpZCI6IjNjNDg5ZTRhLWMyOWMtNDY1YS05YzA1LTM1MzExMzI2NDRmYyIsImlhdCI6MTc1MjgyMjcwMywiZXhwIjoxNzUyOTA5MTAzfQ.e5bPTrLk5_J00RWR13ItFiK_3LZRY1nKViqqHyBVwaE' // 静态写死，也可从本地缓存中获取
    };
  },
  methods: {
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.locationName = res.name;
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.address = res.address;
          console.log("选中的地点信息：", res);
        },
        fail: (err) => {
          console.log("选择地点失败：", err);
        }
      });
    },
    onDateChange(e) {
      this.shootDate = e.detail.value;
    },
    onTimeChange(e) {
      this.shootTime = e.detail.value;
    },
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.img = res.tempFilePaths[0];
        }
      });
    },
    // 城市变化时触发，请求景点列表
    async onCityChange(e) {
       


      this.selectedCity = this.cities[e.detail.value];
      this.selectedSpot = '';
      this.selectedSpotId = null;
      
      try {
        const res=await getSpotsByCity(this.selectedCity.id)

        if (res.code === 200) {
          console.log(res.data)
          this.spots = res.data; // 需为 [{ id, name }] 数组
        } else {
          uni.showToast({ title: '获取景点失败', icon: 'none' });
        }
      } catch (err) {
        console.error(err);
        uni.showToast({ title: '网络异常', icon: 'none' });
      }
    },
    // 景点选择
    onSpotChange(e) {

      const spot = this.spots[e.detail.value];
   
      this.selectedSpot = spot;
      this.selectedSpotId = spot.id;
    },
    async submit() {
      if (!this.title || !this.content) {
        return uni.showToast({
          title: '请填写标题和正文',
          icon: 'none'
        });
      }

      if (!this.img) {
        return uni.showToast({
          title: '请上传图片',
          icon: 'none'
        });
      }

      const shootDateTime = this.shootDate && this.shootTime
        ? `${this.shootDate}T${this.shootTime}:00`
        : '';

      const environment = JSON.stringify({
        name: this.locationName,
        latitude: this.latitude,
        longitude: this.longitude,
        address: this.address
      });

      const payload = {
        filePath: this.img,
        address: this.title,
        addressDescription: this.content,
        idea: this.suggestion,
        shotTime: shootDateTime,
        environment,
        token: this.token
      };

      // 如果选中了景点才附带 scenicSpotId
      if (this.selectedSpotId) {
        payload.scenicSpotId = this.selectedSpotId;
      }

      try {
        const response = await uploadPostWithFile(payload);

        let res = JSON.parse(response.data);
        if (res.code == 200) {
          uni.showToast({ title: '发布成功', icon: 'success' });
        } else {
          uni.showToast({ title: res.describe || '发布失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: error.message || '发布失败', icon: 'none' });
      }
    },
    async loadCities(){
       const res=await getAllCities()
       if(res.code===200){
          this.cities=res.data
       }else{
       uni.showToast({
          title: res.describe,
          icon: 'none'
        });
       }
    }
  },
  mounted(){
       this.loadCities()
  }
};
</script>



<style scoped lang="scss">
.publish-container {
  padding: 20rpx;
}

.image-upload {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

.image-box {
  width: 200rpx;
  height: 200rpx;
  background-color: #f0f0f0;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-img {
  width: 100%;
  height: 100%;
}

.add-box {
  background-color: #fafafa;
  border: 1px dashed #ccc;
}

.plus {
  font-size: 60rpx;
  color: #bbb;
}

.input-title,
.input-content {
  width: 100%;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border: 1px solid #eee;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.input-content {
  min-height: 100rpx;
}

.form-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;

  .time {
    flex: 1;
    display: flex;
    gap: 50rpx;
    color: #eae8e8;
  }
}

.label {
  width: 200rpx;
  font-size: 28rpx;
  color: #333;
}

.picker {
  flex: 1;
  font-size: 28rpx;
  color: #666;
}

.submit-btn {
  background-color: rgb(90, 146, 208);
  color: #fff;
  font-size: 32rpx;
  padding: 20rpx 0;
  border-radius: 50rpx;
  margin-top: 40rpx;
}

.location-picker {
  .picker {
    color: #666;
    border: 1px solid #eee;
    border-radius: 10rpx;
    padding: 20rpx;
    font-size: 28rpx;
    background-color: #f9f9f9;
    width: 100%;
  }
}
</style>
